package com.shebei.api.equipment_api_test.http;


import com.alibaba.fastjson.JSONObject;
import com.shebei.api.equipment_api_test.service.HeadParsing;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientFormUrlencoded implements HttpClienInterface{


    @Autowired
    private HeadParsing headParsing;
    @Override
    public String sendRequest(String url, String requestBody, Map<String, String> head) {
        if(requestBody==null){
            return postWithParams( url,  null, head);
        }
        Map param = JSONObject.parseObject(requestBody);

      String res=  postWithParams( url,  param, head);

        return res;
    }



    private String postWithParams(String url, Map<String, String> params,Map<String, String> head) {
        List<NameValuePair> pairs = generatePairs(params);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            HttpPost httpPost = new HttpPost(url);


            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            if (head != null) {
                for (String key : head.keySet()) {
                    httpPost.setHeader(key, String.valueOf(head.get(key)));
                }
            }



            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
            httpPost.setEntity(entity);
            // 由客户端执行(发送)请求
            response = httpClient.execute(httpPost);
            System.out.println("响应状态为:" + response.getStatusLine());
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                resultString=EntityUtils.toString(responseEntity);
                System.out.println("响应内容长度为:" + resultString);
                System.out.println("响应内容为:" + resultString);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    private List<NameValuePair> generatePairs(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return Collections.emptyList();
        }

        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String,String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = String.valueOf(entry.getValue());
            if (key == null) {
                continue;
            }

            pairs.add(new BasicNameValuePair(key, value));
        }

        return pairs;
    }
}
